<script setup>
import NavBar from '@/components/NavBar.vue'
import { ref, onMounted, computed } from 'vue'
import { showSuccessToast, showFailToast } from 'vant'
import { fetchScoreList } from '@/api/score/index.js'
import { useRoute, useRouter } from 'vue-router'
import { useScoreStore } from '@/stores/score.js'
import { Button } from 'vant'
import * as XLSX from 'xlsx'
import { saveQueryRecords, userSendEmail } from '@/api/score/index.js'

const scoreStore = useScoreStore()
const route = useRoute()
const router = useRouter()
const dataList = ref()
onMounted(async () => {
  //目前不做分页，所以一口气取来所有数据
  const response = await fetchScoreList(
    route.query.bil_month,
    route.query.sales_phone_number,
    '1',
    '1000'
  )
  //console.log(response)
  dataList.value = response.data.data.data
  console.log(dataList.value)
  scoreStore.dataList = dataList.value
})
const test = [1, 2, 3, 4]
const handleClick = (index) => {
  router.push(`/score-detail/${index}`)
}
const exportToExcel = () => {
  // 将数据转换为工作sheet
  const worksheet = XLSX.utils.json_to_sheet(sortedDataWithChineseHeaders.value)

  // 创建新工作簿
  const workbook = XLSX.utils.book_new()

  // 将工作sheet添加到工作簿中
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成文件并下载
  XLSX.writeFile(workbook, `${route.query.sales_phone_number + route.query.bil_month}.xlsx`)

  // 保存查询记录
  saveQueryRecords(
    localStorage.getItem('phone'),
    route.query.bil_month,
    route.query.sales_phone_number,
    dataList.value.length
  )
}

const exportToEmail = async () => {
  // 将数据转换为工作sheet
  const worksheet = XLSX.utils.json_to_sheet(sortedDataWithChineseHeaders.value)

  // 创建新工作簿
  const workbook = XLSX.utils.book_new()

  // 将工作sheet添加到工作簿中
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件的二进制数据
  const excelBuffer = XLSX.write(workbook, {
    bookType: 'xlsx',
    type: 'array' // 获取二进制数组
  })

  // 创建Blob对象
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
  // 创建FormData实例
  const formData = new FormData()

  // 向formData对象添加键值对
  formData.append('phone', route.query.sales_phone_number)

  // 将Blob对象添加到FormData中，并指定文件名
  formData.append(
    'attachment',
    blob,
    `${route.query.sales_phone_number}-${route.query.bil_month}.xlsx`
  )

  const response = await userSendEmail(formData)
  if (response.data.code == 200) {
    showSuccessToast(response.data.msg)
  } else {
    showFailToast(response.data.msg)
  }
  console.log(response)

  // 保存查询记录
  saveQueryRecords(
    localStorage.getItem('phone'),
    route.query.bil_month,
    route.query.sales_phone_number,
    dataList.value.length
  )
}

// 中文表头映射
const chineseHeaders = [
  '积分',
  '积分方案',
  '原始账期',
  '奖励/扣回/激励',
  '积分类型',
  '本地激励',
  '营销工号',
  '资产业务号码',
  '营销人员手机号码',
  'asset_integ_id',
  '积分类型编码',
  '扣回规则',
  '销售品',
  '积分策略',
  '营销人员',
  '人员支局',
  '数据更新日期',
  '账期',
  '人员县分',
  '调整原因'
]

// 英文属性名
const englishKeys = [
  'SCORE',
  'score_offer_name',
  'org_bil_month',
  'jf_type',
  'NEW_SCORE_TYPE_NAME',
  'bdjl',
  'sales_emp_code',
  'acc_nbr',
  'sales_phone_number',
  'asset_integ_id',
  'NEW_SCORE_TYPE_id',
  'fine_rule_name',
  'prom_name',
  'score_strategy_name',
  'sales_employee_name',
  'zj_area_name',
  'update_dt',
  'bil_month',
  'fj_area_name',
  'adjust_reason'
]

// 计算属性：对数据进行排序
const sortedData = computed(() => {
  return dataList.value
    .slice() // 创建副本以避免修改原始数据
    .sort((a, b) => {
      // 先按 jf_type 排序
      if (a.jf_type < b.jf_type) return -1
      if (a.jf_type > b.jf_type) return 1
      // 如果 jf_type 相同，再按 acc_nbr 排序
      return a.acc_nbr.localeCompare(b.acc_nbr)
    })
})

// 计算属性：将排序后的数据映射为中文表头
const sortedDataWithChineseHeaders = computed(() => {
  return sortedData.value.map((item) => {
    const newItem = {}
    englishKeys.forEach((key, index) => {
      newItem[chineseHeaders[index]] = item[key]
    })
    return newItem
  })
})
</script>

<template>
  <NavBar name="积分查询"></NavBar>

  <div class="export-container">
    <!-- <van-button type="export-button" class="export-button" size="small" @click="exportToExcel()"
      >下载（不建议在掌翼使用）</van-button
    > -->
    <van-button type="export-button2" class="export-button" size="small" @click="exportToEmail()"
      >发送至邮箱</van-button
    >
  </div>
  <div class="table-container">
    <!-- 表头 -->
    <div class="table-row header">
      <div class="table-cell column1">月份</div>
      <div class="table-cell column2">资产业务号码</div>
      <div class="table-cell column3">积分类型</div>
      <div class="table-cell column4">积分</div>
    </div>
    <div
      v-for="(data, index) in dataList"
      :key="index"
      class="table-row data"
      @click="handleClick(index)"
    >
      <div class="table-cell column1">{{ route.query.bil_month }}</div>
      <div class="table-cell column2">{{ data.acc_nbr }}</div>
      <div class="table-cell column3">{{ data.jf_type }}</div>
      <div class="table-cell column4">{{ data.SCORE }}</div>
    </div>
    <!-- 示例数据展示 -->
    <!-- <div v-for="t in test" :key="t" class="table-row">

    </div> -->
  </div>
</template>

<style scoped>
.export-button {
  float: right; /* 浮动到右侧 */
  margin-left: 10px;
}

.table-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.table-row {
  display: flex;
}

.table-cell {
  min-width: 15vw;
  padding: 10px;
  text-align: center;
  border: 1px solid #ddd; /* 添加边框以区分每个单元格 */
}

.header {
  font-weight: bold;
  background-color: #e8f2fb; /* 表头背景色 */
  color: #3480cb;
}
.column1 {
  width: 20vw;
}
.column2 {
  width: 40vw;
}
.column3 {
  width: 30vw;
}
.column4 {
  width: 10vw;
}
.data:hover {
  color: #3480cb;
  /* text-decoration: underline; */
  /* text-decoration-color: orange;
  text-decoration-style: dotted;  */
}
</style>
